package com.lyhlmj.oop_client.Style.Buttons.LoginFrameButton;

import com.lyhlmj.oop_client.ClientOperation.ClientUtil.Client;
import com.lyhlmj.oop_client.Style.Buttons.GeneralButton;
import com.lyhlmj.oop_client.Utils.Request;
import com.lyhlmj.oop_client.Frames.WaitFrame.WaitFrame;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;

public class LoginButton extends GeneralButton {
    private Window owner;

    public LoginButton(String str, Window owner) {
        super(str);
        this.owner = owner;
    }

    //设置登陆事件
    public void doLogin(String username, String password) {
        //本地连接127.0.0.1
//        Client client = new Client("192.168.43.61", 2022); //用于连接的创建
        //远程连接时填写服务器的server
        Client.client.setServer("192.168.43.61");
        Client.client.setPort(2022);
        Client client = Client.client; //用于连接的创建
        JSONObject json = Request.getJsonObject("login", "username", username, "password", password);

        client.send(json, new Client.Callback() {
            @Override
            public void onResult(int status, String reason, JSONObject data) {  //回调函数
                if (status != 0) {  //服务器处理出现问题
                    JOptionPane.showMessageDialog(owner, reason);
                    return;
                }
                client.setUsername(data.getString("username"));  //设置当前登陆的用户名

                System.out.println("用户" + username + "登陆成功！\n");

                owner.dispose();  //销毁登陆框架
                JOptionPane.showMessageDialog(owner, reason);  //告知用户登陆成功
                WaitFrame.initial();  //进入五子棋游戏大厅框架
            }
        });
    }
}
